const express = require('express');
const Router = express.Router();

const mongoose = require('mongoose');
require("./model_chat.js");
const Chat = mongoose.model("chatSchema");

require('./model_user.js');
const User = mongoose.model("userSchema");

Router.get('/chatlist',(req,res)=>{
    const userId = req.cookies.COOKIEID;
    User.find({},(err,user)=>{
        let userObj = {};
        user.forEach(item=>{
            userObj[item._id] = {
                name:item.name,
                avatar:item.avatar
            }
        })
        Chat.find({'$or':[{from:userId},{to:userId}]},(err,data)=>{
            if(!err){
                return res.json({
                    code:0,
                    data:data,
                    users:userObj
                })
            }
        })
    })
})

/**
 * 标记已读
 */
Router.post('/read',(req,res)=>{
    const userId = req.cookies.COOKIEID;
    const toId = req.body.toId;
    console.log(userId);
    console.log(toId);
    // 标记消息——对方发给自己的
    Chat.updateMany({from:toId,to:userId},
        {"$set":{read:true}},
        {'multi':true},
        (err,rel)=>{
        if(err){
            console.log(err)
        }
        res.json({
            code:0,
            readnum:rel.nModified,
            msg:'获取成功'
        })
        
    })
})

// 清空
Router.get('/remove',(req,res)=>{
    Chat.remove({}).then((data) => {
        return res.json({
            code:0,
            data:data,
            msg:'数据清除成功'
        })
    })
})
module.exports = Router;